import http from './http'

export interface Question {
  id: number
  courseId: number
  title: string
  content: string
  questionType: 'SINGLE_CHOICE' | 'MULTIPLE_CHOICE' | 'TRUE_FALSE' | 'FILL_BLANK' | 'ESSAY'
  options?: string | { content: string }[] // 后端返回string，前端处理为数组
  correctAnswers: any
  explanation?: string
  difficulty: 'EASY' | 'MEDIUM' | 'HARD'
  points: number
  createdBy: number
  creatorName?: string
  createdAt: string
  updatedAt: string
}

export interface Exam {
  id: number
  courseId: number
  courseName?: string
  title: string
  description?: string
  examType: 'QUIZ' | 'MIDTERM' | 'FINAL' | 'PRACTICE'
  timeLimit?: number
  totalPoints: number
  passScore: number
  maxAttempts: number
  startTime?: string
  endTime?: string
  status: 'DRAFT' | 'PUBLISHED' | 'ARCHIVED'
  showResult: boolean
  showCorrectAnswers: boolean
  shuffleQuestions: boolean
  shuffleOptions: boolean
  createdBy: number
  creatorName?: string
  createdAt: string
  updatedAt: string
  questionCount?: number
  attemptCount?: number
  averageScore?: number
  userAttempts?: number
  canTakeExam?: boolean
  latestRecord?: ExamRecord
  questions?: ExamQuestion[]
}

export interface ExamQuestion {
  id: number
  questionId: number
  orderNo: number
  points: number
  question: Question
}

export interface ExamRecord {
  id: number
  examId: number
  examTitle?: string
  userId: number
  userName?: string
  attemptNumber: number
  startTime: string
  submitTime?: string
  timeSpent: number
  status: 'IN_PROGRESS' | 'SUBMITTED' | 'TIMEOUT' | 'CANCELLED'
  totalScore: number
  totalPoints: number
  percentage?: number
  passStatus: 'PENDING' | 'PASSED' | 'FAILED'
  autoGraded: boolean
  manualGraded: boolean
  gradedBy?: number
  graderName?: string
  gradedAt?: string
  feedback?: string
  createdAt: string
  updatedAt: string
  answers?: ExamAnswer[]
}

export interface ExamAnswer {
  id: number
  questionId: number
  userAnswer: any
  correctAnswer?: any
  isCorrect: boolean
  score: number
  manualScore?: number
  feedback?: string
  question: Question
}

export interface ExamStats {
  examId: number
  participantCount: number
  recordCount: number
  averageScore: number
  averagePercentage: number
  passCount: number
  failCount: number
  passRate: number
}

export interface QuestionRequest {
  courseId: number
  title: string
  content: string
  questionType: 'SINGLE_CHOICE' | 'MULTIPLE_CHOICE' | 'TRUE_FALSE' | 'FILL_BLANK' | 'ESSAY'
  options?: Record<string, string>
  correctAnswers: any
  explanation?: string
  difficulty?: 'EASY' | 'MEDIUM' | 'HARD'
  points?: number
}

export interface ExamRequest {
  courseId: number
  title: string
  description?: string
  examType?: 'QUIZ' | 'MIDTERM' | 'FINAL' | 'PRACTICE'
  timeLimit?: number
  passScore?: number
  maxAttempts?: number
  startTime?: string
  endTime?: string
  showResult?: boolean
  showCorrectAnswers?: boolean
  shuffleQuestions?: boolean
  shuffleOptions?: boolean
  totalPoints?: number
  questions: Array<{
    questionId: number
    orderNo: number
    points: number
  }>
}

export interface ExamSubmitRequest {
  recordId: number
  answers: Array<{
    questionId: number
    answer: any
  }>
}

// 题库API
export const questionApi = {
  // 创建题目
  create: (data: QuestionRequest) => 
    http.post<Question>('/v1/exams/questions', data),

  // 更新题目
  update: (id: number, data: QuestionRequest) => 
    http.put<Question>(`/v1/exams/questions/${id}`, data),

  // 删除题目
  delete: (id: number) => 
    http.delete(`/v1/exams/questions/${id}`),

  // 搜索题目
  search: (params: {
    page?: number
    pageSize?: number
    courseId?: number
    questionType?: string
    difficulty?: string
    keyword?: string
  }) => http.get<{ content: Question[], totalElements: number }>('/v1/exams/questions/search', { params }),

  // 获取题目
  get: (id: number) => 
    http.get<Question>(`/v1/exams/questions/${id}`),

  // 获取课程题目列表
  getByCourse: (courseId: number, params?: {
    questionType?: string
    keyword?: string
    page?: number
    pageSize?: number
  }) => 
    http.get<{ content: Question[], totalElements: number }>(`/v1/exams/courses/${courseId}/questions`, { params })
}

// 考试API
export const examApi = {
  // 创建考试
  create: (data: ExamRequest): Promise<Exam> => 
    http.post<Exam>('/v1/exams', data).then(r => r as unknown as Exam),

  // 更新考试
  update: (id: number, data: ExamRequest): Promise<Exam> => 
    http.put<Exam>(`/v1/exams/${id}`, data).then(r => r as unknown as Exam),

  // 删除考试
  delete: (id: number): Promise<void> => 
    http.delete(`/v1/exams/${id}`).then(() => undefined),

  // 发布考试
  publish: (id: number): Promise<void> => 
    http.post(`/v1/exams/${id}/publish`).then(() => undefined),

  // 归档考试
  archive: (id: number): Promise<void> => 
    http.post(`/v1/exams/${id}/archive`).then(() => undefined),

  // 搜索考试
  search: (params: {
    page?: number
    pageSize?: number
    courseId?: number
    examType?: string
    status?: string
    keyword?: string
  }): Promise<{ content: Exam[], totalElements: number }> => 
    http.get<{ content: Exam[], totalElements: number }>('/v1/exams/search', { params })
      .then(r => r as unknown as { content: Exam[], totalElements: number }),

  // 获取考试
  get: (id: number): Promise<Exam> => 
    http.get<Exam>(`/v1/exams/${id}`).then(r => r as unknown as Exam),

  // 获取课程考试列表
  getByCourse: (courseId: number, params?: {
    page?: number
    pageSize?: number
  }): Promise<{ content: Exam[], totalElements: number }> => 
    http.get<{ content: Exam[], totalElements: number }>(`/v1/exams/courses/${courseId}`, { params })
      .then(r => r as unknown as { content: Exam[], totalElements: number }),

  // 开始考试
  start: (examId: number): Promise<ExamRecord> => 
    http.post<ExamRecord>(`/v1/exams/${examId}/start`).then(r => r as unknown as ExamRecord),

  // 提交考试
  submit: (data: ExamSubmitRequest): Promise<ExamRecord> => 
    http.post<ExamRecord>('/v1/exams/submit', data).then(r => r as unknown as ExamRecord),

  // 获取考试记录
  getRecord: (recordId: number): Promise<ExamRecord> => 
    http.get<ExamRecord>(`/v1/exams/records/${recordId}`).then(r => r as unknown as ExamRecord),

  // 获取考试答案详情
  getAnswers: (recordId: number): Promise<any[]> => 
    http.get<any[]>(`/v1/exams/records/${recordId}/answers`).then(r => r as unknown as any[]),

  // 获取我的考试记录
  getMyRecords: (params?: {
    page?: number
    pageSize?: number
  }): Promise<{ content: ExamRecord[], totalElements: number }> => 
    http.get<{ content: ExamRecord[], totalElements: number }>('/v1/exams/my-records', { params })
      .then(r => r as unknown as { content: ExamRecord[], totalElements: number }),

  // 获取考试题目
  getExamQuestions: (examId: number): Promise<Question[]> => 
    http.get<Question[]>(`/v1/exams/${examId}/questions`).then(r => r as unknown as Question[]),

  // 获取考试统计
  getStats: (examId: number): Promise<ExamStats> =>
    http.get<ExamStats>(`/v1/exams/${examId}/stats`).then(r => r as unknown as ExamStats),

  // 获取学生考试列表
  getStudentExams: (params?: {
    courseId?: number
    status?: string
    page?: number
    pageSize?: number
  }): Promise<{ content: Exam[], totalElements: number }> => 
    http.get<{ content: Exam[], totalElements: number }>('/v1/exams/student', { params })
      .then(r => r as unknown as { content: Exam[], totalElements: number })
}
